package com.example.simplemybatisspringboot.controller;

import com.example.simplemybatisspringboot.entity.Person;
import com.example.simplemybatisspringboot.service.TestService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class TestController {
    @Autowired
    TestService testService;

    @GetMapping("/info/{name}")
    @ResponseBody
    public String getInfo(@PathVariable String name) throws JsonProcessingException {
        Person person = testService.getInfoByName(name);
        ObjectMapper jsonUtil = new ObjectMapper();
        return jsonUtil.writeValueAsString(person);
    }

    @GetMapping("/infos")
    @ResponseBody
    public String getInfos() throws JsonProcessingException {
        List<Person> infos = testService.getInfos();
        ObjectMapper jsonUtil = new ObjectMapper();
        return jsonUtil.writeValueAsString(infos);
    }

    @GetMapping("/addition")
    @ResponseBody
    public String addPerson(){
        for (int i = 0; i < 10; i++) {
            Person p = new Person();
            p.setName("personName:" + i);
            testService.addPerson(p);
        }
        return "Success";
    }
}
